package com.xzzz.irda.guardcat.server.setting;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xzzz.common.base.exception.XzException400;
import com.xzzz.common.base.exception.XzException404;
import com.xzzz.common.base.util.BeanUtil;
import com.xzzz.irda.guardcat.server.repos.mysql.mappers.AlertSettingMapper;
import com.xzzz.irda.guardcat.server.repos.mysql.pojo.AlertSettingMySQLEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class AlertSettingManagerInMySQL implements AlertSettingManager {

    @Autowired
    private AlertSettingMapper alertSettingMapper;

    @Override
    public boolean save(AlertSetting alertSetting) {
        XzException400.throwBy(StrUtil.isBlank(alertSetting.getAppName()), "应用名称不得为空");

        AlertSettingMySQLEntity curSetting = alertSettingMapper
                .selectOne(new QueryWrapper<AlertSettingMySQLEntity>().eq("app_name", alertSetting.getAppName()));

        AlertSettingMySQLEntity updSetting = BeanUtil.toObj(alertSetting, AlertSettingMySQLEntity.class);
        if (curSetting != null) {
            updSetting.setId(curSetting.getId());
            return alertSettingMapper.updateById(updSetting) > 0;
        } else {
            updSetting.setId(null);
            return alertSettingMapper.insert(updSetting) > 0;
        }
    }

    @Override
    public AlertSetting get(String appName) {
        XzException400.throwBy(StrUtil.isBlank(appName), "应用名称不得为空");
        QueryWrapper<AlertSettingMySQLEntity> where = new QueryWrapper<>();
        where.eq("app_name", appName);
        AlertSettingMySQLEntity setting = alertSettingMapper.selectOne(where);
        XzException404.throwBy(setting == null, String.format("[%s]配置不存在", appName));
        return BeanUtil.toObj(setting, AlertSetting.class);
    }
}
